package com.hue.gulimail.gulimailmember.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.hue.common.utils.HttpUtils;
import com.hue.common.utils.R;
import com.hue.gulimail.gulimailmember.entity.MemberLevelEntity;
import com.hue.gulimail.gulimailmember.exception.EmailExistException;
import com.hue.gulimail.gulimailmember.exception.UsernameExistException;
import com.hue.gulimail.gulimailmember.exception.UsernamePasswordErrorException;
import com.hue.gulimail.gulimailmember.feign.OrderFeignService;
import com.hue.gulimail.gulimailmember.service.MemberLevelService;
import com.hue.gulimail.gulimailmember.vo.LoginVo;
import com.hue.gulimail.gulimailmember.vo.OrderVo;
import com.hue.gulimail.gulimailmember.vo.RegisterVo;
import com.hue.gulimail.gulimailmember.vo.SocialUserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.lang.reflect.Member;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hue.common.utils.PageUtils;
import com.hue.common.utils.Query;

import com.hue.gulimail.gulimailmember.dao.MemberDao;
import com.hue.gulimail.gulimailmember.entity.MemberEntity;
import com.hue.gulimail.gulimailmember.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {
    @Autowired
    private MemberLevelService memberLevelService;
    @Autowired
    private OrderFeignService orderFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void register(RegisterVo registerVo) throws UsernameExistException, EmailExistException {
        //判断用户名是否存在
        usernameExist(registerVo.getUsername());
        //判断邮箱是否存在
        emailExist(registerVo.getEmail());

        //查询默认的会员等级信息
        MemberLevelEntity defaultMemberLevel = memberLevelService.defaultMemberLevel();

        MemberEntity member = new MemberEntity();
        member.setUsername(registerVo.getUsername());
        member.setEmail(registerVo.getEmail());
        //对密码使用盐值加密
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        member.setPassword(encoder.encode(registerVo.getPassword()));
        member.setLevelId(defaultMemberLevel.getId());

        //保存用户
        save(member);
    }

    @Override
    public void usernameExist(String username) throws UsernameExistException {
        QueryWrapper<MemberEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        if (list(wrapper).size() > 0) {
            throw new UsernameExistException();
        }
    }

    @Override
    public void emailExist(String email) throws EmailExistException {
        QueryWrapper<MemberEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("email", email);
        if (list(wrapper).size() > 0) {
            throw new EmailExistException();
        }
    }

    @Override
    public MemberEntity login(LoginVo loginVo) throws UsernamePasswordErrorException {
        QueryWrapper<MemberEntity> wrapper = new QueryWrapper<>();
        wrapper.and(w -> {
            w.eq("username", loginVo.getUsername()).or().eq("email", loginVo.getUsername());
        });
        MemberEntity member = getOne(wrapper);

        if (member == null) {
            throw new UsernamePasswordErrorException();
        }

        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if (!encoder.matches(loginVo.getPassword(), member.getPassword())) {
            throw new UsernamePasswordErrorException();
        }

        return member;
    }

    @Override
    public MemberEntity login(SocialUserVo socialUserVo) {
        //判断当前社交用户在本系统中是否注册过
        QueryWrapper<MemberEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("social_uid", socialUserVo.getUid());
        MemberEntity member = getOne(wrapper);

        //当前社交用户第一次登录
        if (member == null) {
            //获取用户的社交信息，注册到本系统
            JSONObject jsonObject = HttpUtils.doGet("https://api.weibo.com/2/users/show.json?" +
                    "access_token=" + socialUserVo.getAccess_token() +
                    "&uid=" + socialUserVo.getUid(), JSONObject.class);

            //注册
            MemberEntity insertMember = new MemberEntity();
            insertMember.setLevelId(1L);
            insertMember.setUsername((String) jsonObject.get("name"));
            insertMember.setNickname((String) jsonObject.get("name"));
            insertMember.setHeader((String) jsonObject.get("avatar_large"));
            insertMember.setAccessToken(socialUserVo.getAccess_token());
            insertMember.setExpiresIn(socialUserVo.getExpires_in());
            insertMember.setSocialUid(socialUserVo.getUid());
            save(insertMember);
            return getOne(wrapper);
        }

        //更新当前用户的uid/access_token/expires_in
        MemberEntity updateMember = new MemberEntity();
        updateMember.setId(member.getId());
        updateMember.setAccessToken(socialUserVo.getAccess_token());
        updateMember.setExpiresIn(socialUserVo.getExpires_in());
        updateById(updateMember);

        //返回当前用户
        return member;
    }

    @Override
    public List<OrderVo> getOrders() {
        R r = orderFeignService.memberOrder();
        if ((Integer) r.get("code") == 0) {
            return r.getData(new TypeReference<List<OrderVo>>() {
            });
        }
        return null;
    }
}
